package cn.hxzy.teacher.service.impl;

import cn.hxzy.common.config.OssConfig;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.ByteArrayInputStream;
import java.io.IOException;

@Service
public class OssService {

    @Value("${oss.endpoint}")
    private String endpoint;
    @Value("${oss.bucket-name}")
    private String bucketName;

    private  OSS ossClient;
    private final OssConfig config;

    @Autowired
    public OssService(OssConfig config) {
        this.config = config;
        this.ossClient = null; // 初始化将在 @PostConstruct 中完成
    }

    @PostConstruct
    public void init() {
        ossClient = new OSSClientBuilder().build(config.getEndpoint(), config.getKeyId(), config.getKeySecret());
    }

    @PreDestroy
    public void shutdown() {
        if (ossClient != null) {
            ossClient.shutdown();
        }
    }

    public String uploadFile(MultipartFile file) throws IOException {
        String originalFileName = file.getOriginalFilename();
        byte[] data = file.getBytes();

        String uniqueFileName =originalFileName;

        // 使用 ByteArrayInputStream 将字节数组包装成 InputStream
        ByteArrayInputStream inputStream = new ByteArrayInputStream(data);

        // 创建一个 PutObjectRequest 对象
        PutObjectRequest putObjectRequest = new PutObjectRequest(config.getBucketName(), uniqueFileName, inputStream);
        // 上传文件
        PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
        String url = "https://" + bucketName + "." + endpoint.replace("http://", "").replace("https://", "") + "/"+uniqueFileName;
        return url;
    }
}
